package com.ibeeking.found.cop.b.rest.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ibeeking.found.common.constants.GlobalConstant;
import com.ibeeking.found.common.utils.UserUtils;
import com.ibeeking.found.cop.b.rest.service.IGroupQrcodeClassService;
import com.ibeeking.found.cop.b.rest.service.IGroupQrcodeService;
import com.ibeeking.found.cop.service.common.dos.GroupQrcodeClassDO;
import com.ibeeking.found.cop.service.common.param.GroupQrcodeClassParam;
import com.ibeeking.found.cop.service.common.query.GroupQrcodeClassQuery;
import com.ibeeking.found.cop.service.common.vo.GroupQrcodeClassVO;
import com.ibeeking.found.cop.service.mapper.GroupQrcodeClassMapper;
import com.ibeeking.found.id.GenerateId;
import com.ibeeking.nematos.core.utils.SpringBeanUtil;
import com.ibeeking.nematos.exception.BusinessException;
import com.ibeeking.nematos.utils.bean.BeanUtil;
import com.ibeeking.nematos.utils.data.Collections3;
import com.ibeeking.nematos.utils.data.TreeFastUtils;
import com.ibeeking.nematos.utils.json.JsonUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;


/**
 * @ClassName GroupQrcodeClassServiceImpl
 * @Description
 * @Author ibeeking
 * @Date 2021-01-27 18:50
 **/
@Service
public class GroupQrcodeClassServiceImpl extends ServiceImpl<GroupQrcodeClassMapper, GroupQrcodeClassDO> implements IGroupQrcodeClassService {

    @Resource
    private GroupQrcodeClassMapper groupQrcodeClassMapper;

    @Resource
    private IGroupQrcodeService groupQrcodeServiceImpl;

    @Override
    public List<GroupQrcodeClassVO> list(GroupQrcodeClassQuery query){
        List<GroupQrcodeClassVO> groupQrcodeClassVOS = new ArrayList<>();
        LambdaQueryWrapper<GroupQrcodeClassDO> queryWrapper = new LambdaQueryWrapper<>(GroupQrcodeClassDO.class)
                .eq(query.getId()!= null, GroupQrcodeClassDO::getId, query.getId())
                .eq(query.getParentId() != null, GroupQrcodeClassDO::getParentId, query.getParentId())
                .eq(StringUtils.isNotEmpty(query.getName()), GroupQrcodeClassDO::getName, query.getName())
                .eq(query.getRoot()!= null, GroupQrcodeClassDO::getRoot, query.getRoot())
                .eq(query.getFixed()!= null, GroupQrcodeClassDO::getFixed, query.getFixed())
                .orderByAsc(GroupQrcodeClassDO::getCreateTime);
        List<GroupQrcodeClassDO> GroupQrcodeClassDOS = groupQrcodeClassMapper.selectList(queryWrapper);
        if(Collections3.isNotEmpty(GroupQrcodeClassDOS)) {
            groupQrcodeClassVOS = GroupQrcodeClassDOS.stream().map(d->{
                GroupQrcodeClassVO groupQrcodeClassVO = BeanUtil.convertBean(d, GroupQrcodeClassVO.class);
                Integer qrcodeCount = groupQrcodeServiceImpl.summaryCount(d.getId());
                groupQrcodeClassVO.setQrcodeNum(qrcodeCount);
                return groupQrcodeClassVO;
            }).collect(Collectors.toList());
        }

        return groupQrcodeClassVOS;
    }

    @Override
    public List<Long> getDepartmentIdWithSubByParentId(Long parentId){
        if (null == parentId) return Collections3.emptyList();

        LambdaQueryWrapper<GroupQrcodeClassDO> queryWrapper = new LambdaQueryWrapper<>(GroupQrcodeClassDO.class);
        queryWrapper.eq(GroupQrcodeClassDO::getParentId, parentId);

        List<GroupQrcodeClassDO> GroupQrcodeClassDOS = groupQrcodeClassMapper.selectList(queryWrapper);
        if (Collections3.isEmpty(GroupQrcodeClassDOS)) {
            return Collections3.emptyList();
        }
        List<Long> ids = GroupQrcodeClassDOS.stream().map(GroupQrcodeClassDO::getId).collect(Collectors.toList());

        //查询所有
        if(Collections3.isNotEmpty(ids) && ids.size() >0 ) {
            for(Long id:ids){
                if (id != null) {
                    List<Long> subIds = getBean().getDepartmentIdWithSubByParentId(id);
                    ids.addAll(subIds);
                }
            };
        }
        ids.add(parentId);
        return ids;
    }

    @Override
    public List<GroupQrcodeClassVO> listByParentId(Long parentId){
        if (null == parentId) {
            parentId = GlobalConstant.PARENT_ID;
        }
        LambdaQueryWrapper<GroupQrcodeClassDO> queryWrapper = new LambdaQueryWrapper<>(GroupQrcodeClassDO.class);
        queryWrapper.eq(GroupQrcodeClassDO::getParentId, parentId);

        List<GroupQrcodeClassDO> GroupQrcodeClassDOS = groupQrcodeClassMapper.selectList(queryWrapper);
        if (Collections3.isEmpty(GroupQrcodeClassDOS)) {
            return Collections3.emptyList();
        }
        List<Long> ids = GroupQrcodeClassDOS.stream().map(GroupQrcodeClassDO::getId).collect(Collectors.toList());
        ids.add(parentId);
        //查询所有
        List<GroupQrcodeClassDO> allGroupQrcodeClassDOS = groupQrcodeClassMapper.selectList(new LambdaQueryWrapper<>(GroupQrcodeClassDO.class)
                .orderByAsc(GroupQrcodeClassDO::getCreateTime)
                .orderByDesc(GroupQrcodeClassDO::getSort)
        );
        List<GroupQrcodeClassVO> allGroupQrcodeClassTrees = JsonUtils.jsonToList(allGroupQrcodeClassDOS, GroupQrcodeClassVO.class);
        if(Collections3.isNotEmpty(allGroupQrcodeClassTrees)) {
            allGroupQrcodeClassTrees.stream().forEach(d->{
                Integer qrcodeCount = groupQrcodeServiceImpl.summaryCount(d.getId());
                d.setQrcodeNum(qrcodeCount);
            });
        }
        List<Long> result = new ArrayList<>();
        TreeFastUtils.selectLongCidByPid(result, allGroupQrcodeClassTrees, ids);
        result.addAll(ids);
        allGroupQrcodeClassTrees = allGroupQrcodeClassTrees.stream().filter(g -> result.contains(g.getId())).collect(Collectors.toList());
        List<GroupQrcodeClassVO>  GroupQrcodeClassVOS = TreeFastUtils.listToTree(allGroupQrcodeClassTrees, parentId);

        return  GroupQrcodeClassVOS;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Boolean add(GroupQrcodeClassParam param) {
        checkUnique(param);
        GroupQrcodeClassDO entityDO = BeanUtil.convertBean(param, GroupQrcodeClassDO.class);
        Long id = GenerateId.generateId();
        entityDO.setId(id);
        entityDO.setFixed(0);
        entityDO.setRoot(0);
        entityDO.setSort(id);
        entityDO.setCreateBy(UserUtils.getUserId());
        entityDO.setCreateTime(LocalDateTime.now());
        entityDO.setModifyTime(LocalDateTime.now());
        return groupQrcodeClassMapper.insert(entityDO) > 0;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Boolean modify(GroupQrcodeClassParam param) {
        GroupQrcodeClassDO entityDO = BeanUtil.convertBean(param, GroupQrcodeClassDO.class);
        entityDO.setModifyBy(UserUtils.getUserId());
        entityDO.setModifyTime(LocalDateTime.now());
        entityDO.setFixed(0);
        entityDO.setRoot(0);
        return groupQrcodeClassMapper.updateById(entityDO) > 0;
    }

    @Override
    public GroupQrcodeClassVO view(Long id) {
        GroupQrcodeClassDO entityDO = groupQrcodeClassMapper.selectById(id);
        if(entityDO == null) throw new BusinessException("没有查到相关记录！");
        GroupQrcodeClassVO entityVO = BeanUtil.convertBean(entityDO, GroupQrcodeClassVO.class);
        return entityVO;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Boolean del(Long id) {
        GroupQrcodeClassDO entityDO = groupQrcodeClassMapper.selectById(id);
        if(entityDO == null) throw new BusinessException("没有查到相关记录！");
        return groupQrcodeClassMapper.deleteById(id) > 0;
    }
    /**
     * 校验唯一性
     *
     * @param param
     */
    public void checkUnique(GroupQrcodeClassParam param) {
        if (param == null) {
            throw new BusinessException("当前记录不存在!");
        }
        //code name确保等级唯一性
        LambdaQueryWrapper<GroupQrcodeClassDO> queryWrapper = new LambdaQueryWrapper<GroupQrcodeClassDO>()
                .ne(param.getId() != null, GroupQrcodeClassDO::getId, param.getId())
                .eq(GroupQrcodeClassDO::getName, param.getName());
        List<GroupQrcodeClassDO> dos = groupQrcodeClassMapper.selectList(queryWrapper);
        if (Collections3.isNotEmpty(dos)) {
            throw new BusinessException("已经存在同名的记录!");
        }
    }

    private IGroupQrcodeClassService getBean(){
        return SpringBeanUtil.getBean(GroupQrcodeClassServiceImpl.class);
    }
}
